package pl.edu.agh.winmon.analise;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

import pl.edu.agh.winmon.hibernate.CpuLoad;
import pl.edu.agh.winmon.hibernate.Session;
import pl.edu.agh.winmon.hibernate.Turn;

public class CoreLoadSeriesProvider implements SessionSeriesProvider {

	public TimeSeriesCollection provideSeries(Session session, long start,
			long end) {
		Map<Integer, TimeSeries> timeSeries = new HashMap<Integer, TimeSeries>();
		for (Turn turn : session.getTurns()) {
			if (turn != null) {
				if (turn.getStartTime() >= start && turn.getStartTime() < end) {
					Double value = 0.0;
					for (CpuLoad cpuLoad : turn.getCpusLoads()) {
						if (cpuLoad != null && cpuLoad.getCpuNumber() != null) {
							value = cpuLoad.getCpuLoad();

							value = value * 100;
							if (timeSeries.get(cpuLoad.getCpuNumber()) == null) {
								timeSeries.put(
										cpuLoad.getCpuNumber(),
										new TimeSeries("Core "
												+ cpuLoad.getCpuNumber()
												+ " load"));
							}
							timeSeries.get(cpuLoad.getCpuNumber()).addOrUpdate(
									new Second(new Date(turn.getStartTime())),
									value);
						}
					}

				}
			}
		}
		TimeSeriesCollection collection = new TimeSeriesCollection();
		for (TimeSeries ts : timeSeries.values()) {
			collection.addSeries(ts);
		}
		return collection;
	}
}
